import React, { Key, useEffect, useState } from 'react'
import { Card, Space, Table, Tag, Button, Divider, Modal, Form, Input, message, Upload } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { reqAddOrUpdate, reqDeleteTrademark, reqTrademark } from '@/api/product/trademark';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
export default function Trademark() {

  // 存储品牌数据列表
  const [trademarkList, setTrademarkList] = useState<any>([])
  // 分页相关的状态
  const [total, setTotal] = useState<number>(0)
  const [page, setPage] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(3)
  const [open, setOpen] = useState(false);
  const [tmParams,setTmParams] = useState<any>({
    tmName:'',
    logoUrl:'',
    id:''
  })
  
  const [form] = Form.useForm()

  useEffect(() => {
    getTrademark(page, pageSize)
  }, [])
  // 获取品牌数据
  async function getTrademark(page: number, pageSize: number) {
    let result = await reqTrademark(page, pageSize)
    console.log(result);
    setTrademarkList(result.records)
    // setPage(result.current)
    setTotal(result.total)
    // setPageSize(result.pages)
  };


  // 对话框
  const showModal = () => {
    form.setFieldsValue({tmName:'',logoUrl:'',id:''})
    setImageUrl('')
    setTmParams({tmName:'',logoUrl:'',id:''})
    setOpen(true);
  };
  const handleOk = async(e: React.MouseEvent<HTMLElement>) => {
    const params = form.getFieldsValue()
    // console.log(e);
    // console.log(params);
    if(tmParams.id){
      tmParams.tmName = params.tmName,
      tmParams.logoUrl = imageUrl
    }else{
      tmParams.tmName = params.tmName
      tmParams.logoUrl= params.logoUrl.file?.response.data
    }
    // console.log(tmParams);
    await reqAddOrUpdate(tmParams)
    message.success(tmParams.id?'修改成功':'添加成功')
    getTrademark(page,pageSize)
    setOpen(false);
  };

  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    // console.log(e);
    setOpen(false);
  };

  const onFinish = (values: any) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo: any) => {
    // console.log('Failed:', errorInfo);
  };

  const columns: ColumnsType<any> = [
    {
      title: '序号',
      // dataIndex: 'name',
      // key: 'name',
      render: (text, records, index) => {
        // records一定是data中的每一个数据对象
        // index 是data中每一个数据对象的下标

        return index + 1
      },
      align: 'center',
      width: 120
    },
    {
      title: '品牌名称',
      dataIndex: 'tmName',
      align: 'center'
    },
    {
      title: '品牌LOGO',
      render: (trademark) => {
        return (
          <img
            src={trademark.logoUrl}
            alt=""
            width={80}
          />
        )
      },
      align: 'center'
    },
    {
      title: '操作',
      fixed: 'right',
      render: (data) => {
        return (
          <Space>
            <Button type="primary" onClick={()=>{
              setOpen(true)
              setTmParams(data)
              setImageUrl(data.logoUrl)
              form.setFieldsValue({tmName:data.tmName,id:data.id})
              // console.log(data);
            }}>修改</Button>
            <Button type="primary" onClick={async()=>{
               await reqDeleteTrademark(data.id)
                message.success('删除成功')
                getTrademark(page,pageSize)
              }} danger>删除</Button>
          </Space>
        )
      },
      width: 240,
      align: 'center'
    },
  ];
  // 上传图片
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, url => {
        setLoading(false);
        setImageUrl(url);     
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <Card>
      <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>添加</Button>
      <Divider></Divider>
      <Table
        rowKey='id'
        columns={columns}
        dataSource={trademarkList}
        style={{ marginTop: 10 }}
        bordered
        pagination={{
          total,
          current: page,
          pageSize,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [1, 3, 6],
          showTotal: (total) => {
            return `总共：${total}`
          },
          onChange: (page, pageSize) => {
            // console.log(page, pageSize);
            setPage(page)
            setPageSize(pageSize)
            getTrademark(page, pageSize)
          }
        }}
      />


      <Modal
        title={
          tmParams.id?<div>修改品牌</div>:<div>添加品牌</div>
        }
        visible={open}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="品牌名称"
            name="tmName"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="品牌LOGO"
            name="logoUrl"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Upload
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/dev-api/admin/product/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="file" style={{ width: '100%' ,height:'100%'}} /> : uploadButton}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}
